import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_luban/flutter_luban.dart';
// import 'package:image_picker/image_picker.dart';
import 'package:zhaoxiaowu_app/global/global.dart';
import 'package:zhaoxiaowu_app/utils/utils.dart';

class LoveImageViewModel extends ChangeNotifier {
  List _imgs = [];

  List get imgs => _imgs;

  void setImgs(List newValue) {
    _imgs = newValue;
    notifyListeners();
  }

  void getLoveImages() async {
    ToastUtils.showActivity();

    Response result = await Global.shared().get("/zxw/Imgs");

    print(result);

    if (result.data["success"]) {
      setImgs(result.data["data"]);
    } else {
      ToastUtils.showError(result.data["msg"]);
    }
  }

  void uploadImage(pickedFile) async {
    ToastUtils.showActivity("正在上传图片...");
    if (pickedFile != null) {
      print(pickedFile.path);
      File file = File(pickedFile.path);
      CompressObject compressObject = CompressObject(
        imageFile: file,
        path: file.path.substring(
          0,
          file.path.lastIndexOf("/"),
        ),
      );
      Luban.compressImage(compressObject).then((path) async {
        if (path != null) {
          String filename = path.substring(path.lastIndexOf("/") + 1);
          Response result = await Global.shared().post(
            "/zxw/Imgs",
            data: FormData.fromMap(
              {
                "file": await MultipartFile.fromFile(path, filename: filename),
              },
            ),
          );
          if (result.data["success"]) {
            ToastUtils.showSuccess(result.data["msg"]);
            Future.delayed(Duration(seconds: 1), () => getLoveImages());
          } else {
            ToastUtils.showError(result.data["msg"]);
          }
        } else {
          ToastUtils.dismissActivity();
        }
      });
    } else {
      ToastUtils.dismissActivity();
      ToastUtils.showToast("图片不可用");
    }
  }

  void deleteImage(String id) async {
    ToastUtils.showActivity("正在删除图片...");

    Response result = await Global.shared().delete(
      "/zxw/Imgs",
      parameters: {
        "id": id,
      },
    );

    if (result.data["success"]) {
      ToastUtils.showSuccess("删除图片成功");
      Future.delayed(Duration(seconds: 1), () => getLoveImages());
    } else {
      ToastUtils.showError(result.data["msg"]);
    }
  }
}
